//index.js
//获取应用实例
const app = getApp()
let nowIndex = 0;
let winH, winW;
let stauts = 0;

Page({
  data: {
    //imgUrl
    imgUrl:app.globalData.iconImgUrl,
    noData: false,
    rewardNoData: false,
    approvalTabH: 90,
    myhonor: true,
    honorVisible: true,
    personRankVisi: false,
    modalVisible: false,
    comprehensiveRankVisi: false,
    themeRankVisi: false,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    tabH: app.globalData.tabH,
    userInfo: '',
    hasUserInfo: false,
    loading: true,
    awardHonorPoint: '',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    avatarUrl: app.globalData.iconImgUrl+"avater.svg",
    title: "佳积分",
    level: 8,
    noticeList: [{
      id: 'none',
      CONTENT: '暂时没有公告'
    }],
    navTabObj: [{
      name: "认可信息",
      className: 'active'
    },
    {
      name: "悬赏信息",
      className: ''
    }
    ],
    approvelList: [],
    rewardList: [],
    nowTabIndex: 0,
    scrollHeight: 667,
    scrollTop: 0,
    scrollY: true,
    tabH: 0,
    teamRank: [{
      name: "综合排名",
      mark: 0,
      active: false,
      type: 5
    }],
    personRank: [{
      name: "个人综合排名",
      mark: 0,
      active: false,
      type: 1
    },
    {
      name: "本月获取积分排名",
      mark: 0,
      active: false,
      type: 2
    },
    {
      name: "本月获取誉点排名",
      mark: 0,
      active: false,
      type: 3
    },
    {
      name: "本月获取梦想分排名",
      mark: 0,
      active: false,
      type: 4
    }
    ],
    themeRank: [{
      name: "现场组团PK",
      mark: 0,
      active: false
    },
    {
      name: "本月团队人均营业额PK",
      mark: 0,
      active: false
    },
    {
      name: "本月团队总营业额PK",
      mark: 0,
      active: false
    }
    ],
    storeRank: [{
      name: "本月人均营业额排名",
      mark: 0,
      active: false,
      type: 6
    },
    {
      name: "本月综合排名",
      mark: 0,
      active: false,
      type: 7
    }
    ],
    reward: false,
    target: {
      yearTarget: 0,
      yearRestTarget: 0,
      monthTarget: 0,
      monthRestTarget: 0
    },
    currentPage: 1,
    pageSize: 20,
    totalPage: 1,
    rewardCurrentPage: 1,
    rewardPageSize: 20,
    rewardTotalPage: 1,
    timer: null,
    noticeTimer: null
  },
  // 获取未审批条数
  getNoExamine() {
    const that = this
    wx.request({
      // url: app.globalData.baseUrl + 'application/getUnAuditNum.do',
      url: app.globalData.baseUrl + 'application/getsh.do',
      method: 'post',
      data: {
        userCode: wx.getStorageSync('userCode'),
        type:'0'
      },
      success(res) {
        // console.log('未审核条数', res)
        that.setData({
          // unAuditNum: res.data.unAuditNum
          unAuditNum: res.data.page.totalResult
        })
      }
    })
  },
  // 获取认可列表
  getApList() {
    const that = this

    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: app.globalData.baseUrl + 'accept/getApproval.do',
      method: "post",
      data: {
        userCode: wx.getStorageSync('userCode'),
        currentPage: this.data.currentPage,
        pageSize: this.data.pageSize,
        fromType: "byShop"
      },
      success(res) {
        console.log('认可信息', res)
        const historyList = that.data.approvelList
        const requestList = res.data.acceptList
        console.log('requestList',requestList[0])
        var list = that.pushData(historyList, requestList)
        if (res.statusCode === 200) {
          if (list.length > 0) {
            that.setData({
              approvelList: list,
              noData: false,
              totalPage: res.data.page.totalPage
            })
          } else {
            that.setData({
              noData: true
            })
          }
          wx.hideLoading()
        }
      }
    })
  },
  pushData(srcData, oprateData) {
    var tempArr = srcData
    oprateData.forEach(item => {
      tempArr.push(item)
    })
    return tempArr
  },
  // 是否显示誉点赏赐弹窗
  toggleShow(e) {
    const id = e.currentTarget.dataset.id,
      nowAwardIndex = e.currentTarget.dataset.index;

    this.setData({
      modalVisible: !this.data.modalVisible,
      integralID: id,
      nowAwardIndex: nowAwardIndex
    })
  },
  // 输入荣誉点
  honorChange(e) {
    const that = this,
      value = e.detail.value
    if (value !== '') {
      if (value > 3) {
        that.setData({
          awardHonorPoint: ''
        })
      } else {
        that.setData({
          awardHonorPoint: e.detail.value
        })
      }
    }
  },
  // 提交赏赐的誉点
  award() {
    const that = this
    const awardHonorPoint = this.data.awardHonorPoint,
      nowAwardIndex = this.data.nowAwardIndex,
      honor = this.data.honor
    if (awardHonorPoint === '') {
      wx.showToast({
        title: '没有输入誉点',
        image: '/assets/images/icon/error.png'
      })
      return
    }
    var data = {
      "userCode": wx.getStorageSync('userCode'),
      "id": this.data.integralID,
      "num": this.data.awardHonorPoint * 1
    }
    if (data.num > honor) {
      wx.showToast({
        title: '誉点不够',
        image: '/assets/images/icon/error.png'
      })
    } else {
      wx.request({
        url: app.globalData.baseUrl + 'accept/give.do',
        data: data,
        method: 'post',
        success(res) {
          console.log('赏赐', res);
          if (res.data.rstype) {
            that.setData({
              ['approvelList[' + nowAwardIndex + '].isPay']: true,
              modalVisible: false,
              honor: res.data.honor
            })
            wx.showToast({
              title: '提交成功',
            })
          }
        }
      })
    }
  },
  // 是否显示获取权限按钮
  showGetInfo() {
    // console.log(app.globalData.userInfo)
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        avatarUrl: app.globalData.userInfo.avatarUrl
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          avatarUrl: res.userInfo.avatarUrl
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.hideTabBar()

      wx.getUserInfo({
        lang: 'zh_CN',
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true,
            avatarUrl: res.userInfo.avatarUrl
          })
          wx.showTabBar()
        },
        fail: res => {
          console.log(res)
        }
      })
    }
  },
  // 获取用户信息
  getUserInfo(e) {
    console.log(e)
    const userInfo = e.detail.userInfo
    app.globalData.userInfo = userInfo
    this.setData({
      userInfo: userInfo,
      hasUserInfo: true,
      avatarUrl: userInfo.avatarUrl
    })

    // 保存用户数据到数据库
    console.log('openid', wx.getStorageSync("openId"))
    const data = {
      "userCode": wx.getStorageSync("userCode"),
      "openid": wx.getStorageSync("openId"),
      "nickName": userInfo.nickName,
      "headImg": userInfo.avatarUrl
    }
    // console.log("用户数据", data)
    wx.request({
      url: app.globalData.baseUrl + 'employee/saveWechatMsg.do',
      method: 'post',
      data: data,
      success(res) {
        // console.log('用户数据回显', res)
      }
    })
  },
  getInfoById() {
    const that = this

    wx.request({
      url: app.globalData.baseUrl + 'employee/getMyMsg.do',
      method: "post",
      data: {
        userCode: wx.getStorageSync('userCode')
      },
      success(res) {
        // console.log('name', res)
        if (res.statusCode === 200) {
          // console.log('用户信息', res)
          const data = res.data
          let integral = 0, honor = 0, dreamPoint = 0;

          if (data.integrals[0].integral) {
            integral = data.integrals[0].integral
          } else if (data.integrals[1].integral) {
            integral = data.integrals[1].integral
          } else if (data.integrals[2].integral) {
            integral = data.integrals[2].integral
          }

          if (data.integrals[0].honor) {
            honor = data.integrals[0].honor
          } else if (data.integrals[1].honor) {
            honor = data.integrals[1].honor
          } else if (data.integrals[2].honor) {
            honor = data.integrals[2].honor
          }

          if (data.integrals[0].dreamPoint) {
            dreamPoint = data.integrals[0].dreamPoint
          } else if (data.integrals[1].dreamPoint) {
            dreamPoint = data.integrals[1].dreamPoint
          } else if (data.integrals[2].dreamPoint) {
            dreamPoint = data.integrals[2].dreamPoint
          }

          that.setData({
            level: data.level,
            integral: integral,
            honor: honor,
            dreamPoint: dreamPoint,
            userName: data.userName,
            roleId: data.roleId
          })
          app.globalData.phone = data.phone
          app.globalData.sexual = data.gender
          app.globalData.honor = data.integrals[1].honor

          const userInfo = wx.getStorageSync('userInfo')
          console.log('currentYearIntegral', data.currentYearIntegral)
          if (!userInfo) {
            // console.log("本地存储")
            wx.setStorageSync('userInfo', {
              level: data.level,
              integral: data.integrals[0].integral,
              honor: data.integrals[1].honor,
              dreamPoint: data.integrals[2].dreamPoint,
              userName: data.userName,
              phone: data.phone,
              sexual: data.gender,
              roleId: data.roleId,
              jfAmount: data.jfAmount,
              mxfAmount: data.mxfAmount,
              ydAmount: data.ydAmount,
              currentYearIntegral: data.currentYearIntegral,
              avatarUrl: data.headImg
            })
          }

        }
      }
    })
  },
  // 公告轮播
  // playNews() {
  //   let length = this.data.noticeList.length,
  //     that = this;
  //   let interval = 3000;
  //   // console.log(length
  //   clearInterval(that.timer)
  //   that.timer = setInterval(change, interval);

  //   function change() {

  //     if (nowIndex < length - 1) {
  //       nowIndex++;
  //       allSetToZero();
  //       var nowItem = 'noticeList[' + nowIndex + '].top';
  //       that.setData({
  //         [nowItem]: "0"
  //       })
  //     } else {
  //       nowIndex = 0;
  //       allSetToZero();
  //       var nowItem = 'noticeList[0].top';
  //       that.setData({
  //         [nowItem]: "0"
  //       })
  //     }
  //   }

  //   function allSetToZero() {
  //     for (var i = 0; i < length; i++) {
  //       var noticeItem = 'noticeList[' + i + '].top';
  //       that.setData({
  //         [noticeItem]: "66rpx"
  //       })
  //     }
  //   }
  // },
  // 设置tabbar
  initTabBar() {
    // 获取系统状态栏信息
    var that = this
    wx.getSystemInfo({
      success: e => {
        // console.log(e.windowWidth)
        const winW = e.windowWidth
        app.globalData.tabH = e.screenHeight - e.windowHeight
        that.setData({
          tabH: app.globalData.tabH + winW * 0.14
        })
      }
    })
  },
  onPullDownRefresh() {
    //wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getInfoById()
    this.resetPage()
  },
  resetPage() {
    this.getInfoById();
    //获取未审批条数
    this.getNoExamine();
    wx.showLoading({
      title: '加载中...',
    })
    const nowTabIndex = this.data.nowTabIndex
    if (nowTabIndex === 0) {
      this.setData({
        currentPage: 1,
        approvelList: []
      })
      this.getApList()
    } else {
      this.setData({
        rewardCurrentPage: 1,
        rewardList: []
      })
      this.getRewardList()
    }
    setTimeout(function () {
      //wx.hideNavigationBarLoading() //完成停止加载

      wx.hideLoading()
      wx.stopPullDownRefresh() //停止下拉刷新

    }, 1500);
  },
  // 页面跳转
  toPage(e) {
    var url = e.currentTarget.dataset.url;
    var id = e.currentTarget.dataset.id;
    if (id) {
      url = url + "?id=" + id
    }
    // console.log(id, url)
    wx.navigateTo({
      url: url,
    })
  },
  isBottom() {
    this.setData({
      scrollY: false
    })
  },
  //tab点击
  tabClick(e) {
    let tab1 = 'navTabObj[0].className',
      tab2 = 'navTabObj[1].className',
      index = e.target.dataset.index;

    if (index === 0) {
      this.setData({
        [tab1]: "active",
        [tab2]: "",
        reward: false,
        nowTabIndex: index,
        rewardNoData: false,
        currentPage: 1,
        totalPage: 1,
        approvelList: []
      })
      this.getApList()
    } else {
      this.setData({
        [tab2]: "active",
        [tab1]: "",
        noData: false,
        reward: true,
        nowTabIndex: index,
        rewardList: [],
        rewardCurrentPage: 1,
        rewardTotalPage: 1,
      })
      this.getRewardList()
    }

  },
  getRewardList() {
    wx.showLoading({
      title: '加载中...',
    })
    var that = this
    wx.request({
      url: app.globalData.baseUrl + 'reward/getReward.do',
      data: {
        userCode: wx.getStorageSync('userCode'),
        currentPage: that.data.rewardCurrentPage,
        pageSize: that.data.rewardPageSize
      },
      method: 'post',
      success(res) {
        // console.log('悬赏', res)
        const historyList = that.data.rewardList
        const requestList = res.data.rewardList
        var list = that.pushData(historyList, requestList)
        // const list = res.data.rewardList
        if (list.length > 0) {
          that.setData({
            rewardNoData: false,
            rewardList: list,
            rewardTotalPage: res.data.pageInfo.totalPage
          })
        } else {
          that.setData({
            rewardNoData: true
          })
        }

        wx.hideLoading()
      }
    })
  },
  // 点赞
  loveIt(e) {
    let index = e.target.dataset.index,
      like = e.target.dataset.like,
      id = e.target.dataset.id,
      that = this;
    if (like === -1) {

      const nowTabIndex = this.data.nowTabIndex;
      const item = "approvelList[" + index + "]";
      const nowItem = this.data.approvelList[index];

      wx.request({
        url: app.globalData.baseUrl + 'accept/giveLike.do',
        method: 'post',
        data: {
          userCode: wx.getStorageSync('userCode'),
          id: id
        },
        success(res) {
          // console.log('点赞',res)
          if (res.statusCode === 200) {
            that.setData({
              [item + '.like']: 1,
              [item + '.LIKE_NUM']: nowItem.LIKE_NUM + 1
            })
          }
        }
      })

    }
  },
  // 当点击 首页  里面的  荣誉榜 会弹出一个页面
  showHonor() {
    this.setData({
      honorVisible: true
    })
  },
  //隐藏荣耀榜
  hideHonor(e) {
    // console.log(e);
    var tapTarget = e.target.id;
    if (tapTarget === "honor-wrap") {
      this.setData({
        honorVisible: false
      })
    }
  },
  // 荣耀榜点击显示隐藏的方法
  showRank(e) {
    var visiName = e.currentTarget.dataset.visiname;
    var index = e.currentTarget.dataset.index,
      type = e.currentTarget.dataset.type;

    switch (visiName) {
      case 'personRankVisi':
        // boolean = this.data.personRankVisi
        var length = this.data.personRank.length
        for (var i = 0; i < length; i++) {
          var tempItem = "personRank[" + i + "].active"
          this.setData({
            [tempItem]: false
          })
        }
        var item = "personRank[" + index + "].active"
        this.setData({
          [item]: true
        })
        break;
      case 'comprehensiveRankVisi':
        var length = this.data.teamRank.length
        for (var i = 0; i < length; i++) {
          var tempItem = "teamRank[" + i + "].active"
          this.setData({
            [tempItem]: false
          })
        }
        var item = "teamRank[" + index + "].active"
        this.setData({
          [item]: true
        })
        break;
      case 'themeRankVisi':
        // boolean = this.data.themeRankVisi
        var length = this.data.themeRank.length
        for (var i = 0; i < length; i++) {
          var tempItem = "themeRank[" + i + "].active"
          this.setData({
            [tempItem]: false
          })
        }
        var item = "themeRank[" + index + "].active"
        this.setData({
          [item]: true
        })
        break;
      case 'storeRankVisi':
        // console.log('storeRank', index)
        var length = this.data.storeRank.length
        for (var i = 0; i < length; i++) {
          var tempItem = "storeRank[" + i + "].active"
          this.setData({
            [tempItem]: false
          })
        }
        var item = "storeRank[" + index + "].active"
        this.setData({
          [item]: true
        })
        break;
      default:
        break;
    }
    this.setData({
      [visiName]: true
    })

    this.queryRankMes(type)
  },
  queryRankMes(type) {
    const data = {
      userCode: wx.getStorageSync('userCode'),
      type: type
    }
    const that = this
    // console.log(data)
    wx.request({
      url: app.globalData.baseUrl + 'ranking/getRankingList.do',
      method: 'post',
      data: data,
      success(res) {
        // console.log('排名ren', res)
        switch (type) {
          case 1:
            that.setData({
              personRankList: res.data.rankingList
            })
            break
          case 2:
            that.setData({
              personRankList: res.data.rankingList
            })
            break
          case 3:
            that.setData({
              personRankList: res.data.rankingList
            })
            break
          case 4:
            that.setData({
              personRankList: res.data.rankingList
            })
            break
          case 5:
            that.setData({
              teamRankList: res.data.rankingList
            })
            break
          case 6:
            that.setData({
              everyRankList: res.data.rankingList
            })
            break
          case 7:
            that.setData({
              everyRankList: res.data.rankingList
            })
            break
          default:
            break
        }
      }
    })
  },
  //登陆后自动显示隐藏荣誉榜
  autoShowHonor() {
    var that = this;
    this.showHonor();
    setTimeout(hideHonor, 2000);

    function hideHonor() {
      that.setData({
        honorVisible: false
      })
    }
  },
  //点击申请跳转页面到申请页面
  toApply() {
    wx.navigateTo({
      url: '../apply/apply',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  // 审核
  toExamine() {
    const roleId = this.data.roleId
    wx.navigateTo({
      url: '../examine/list',
    })
    // if (roleId === '25' || roleId === '24') {
    //   // wx.showToast({
    //   //   title: '您没有权限哦',
    //   //   image: '/assets/images/icon/error.png'
    //   // })
    //   wx.navigateTo({
    //     url: '../examine/list',
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: '../examine/list',
    //   })
    // }

  },
  onReady() {

  },
  getRankMes() {
    var userCode = wx.getStorageSync('userCode'),
      that = this
    wx.request({
      url: app.globalData.baseUrl + 'ranking/getRanking.do',
      data: {
        userCode: userCode
      },
      method: "post",
      success(res) {
        // console.log('排名', res)
        if (res.data.rstype) {
          const data = res.data
          that.setData({
            target: {
              monthRestTarget: data.monthRestTarget,
              monthTarget: data.monthTarget,
              yearRestTarget: data.yearRestTarget,
              yearTarget: data.yearTarget
            },
            personRank: [{
              name: '个人综合排名',
              mark: data.myMixRanking,
              type: 1
            },
            {
              name: '本月获取积分排名',
              mark: data.myIntegralRanking,
              type: 2
            },
            {
              name: '本月获取誉点排名',
              mark: data.myYDRanking,
              type: 3
            },
            {
              name: '本月获取梦想分排名',
              mark: data.myMXRanking,
              type: 4
            }
            ],
            teamRank: [{
              name: '综合排名',
              mark: data.teamMixRanking,
              type: 5
            }],
            storeRank: [{
              name: '本月人均营业额排名',
              mark: data.avgTurnover,
              type: 6
            },
            {
              name: '本月综合排名',
              mark: data.monthTurnoverRank,
              type: 7
            }
            ]
          })
          // that.getPersonRanking()
        }
      }
    })
  },
  getNotice() {
    var that = this
    wx.request({
      url: app.globalData.baseUrl + 'notice/list.do',
      success(res) {
        console.log('公告notice', res)
        if (res.data.length > 0) {
          that.setData({
            noticeList: res.data
          })
        }
        // that.playNews()
      }
    })
  },
  onLoad() {
    // console.log(app.globalData.tabBarH)
    var timer = null,
      that = this
    that.getRankMes()
    timer = setTimeout(function () {
      //设计tabber
      that.initTabBar()
      //登录后显示荣誉榜
      that.autoShowHonor();
      //是否显示权限按钮
      that.showGetInfo();
      clearTimeout(timer)
    }, 500)
  },
  onShow() {
    this.getNotice()
    // this.getApList();
    this.resetPage()
  },
  onHide() {
    const that = this
    clearInterval(that.timer)
    clearTimeout(that.noticeTimer)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const nowTabIndex = this.data.nowTabIndex
    if (nowTabIndex === 0) {
      // console.log('认可', (currentPage < totalPage))
      const currentPage = this.data.currentPage
      const totalPage = this.data.totalPage
      if (currentPage < totalPage) {
        this.setData({
          currentPage: currentPage + 1
        })
        this.getApList()
      }

    } else {
      console.log('悬赏')
      const rewardCurrentPage = this.data.rewardCurrentPage
      const rewardTotalPage = this.data.rewardTotalPage
      // console.log(rewardCurrentPage, rewardTotalPage)
      if (rewardCurrentPage < rewardTotalPage) {
        this.setData({
          rewardCurrentPage: rewardCurrentPage + 1
        })
        this.getRewardList()
      }
    }
  },
  onPageScroll(event) {
    this.setData({
      scrollTop: event.scrollTop
    })
  },
})